const qs = require('querystring')
const { set, get } = require('./src/db/redis')
const { getExpires, getPostData, access } = require('./src/utils')
const chalk = require('chalk')

// 路由
const handleBlogRouter = require('./src/router/blog')
const handleItemRouter = require('./src/router/item')
const handleUserRouter = require('./src/router/user')
const handleEmptyRouter = require('./src/router/empty')

module.exports = async (req, res) => {
  // 写日志
  if (process.env.NODE_ENV === 'dev') {
    console.log(`${chalk.green(req.method)}  ${chalk.yellow(req.url)}  ${new Date().toLocaleString()}  ${chalk.grey(req.headers['user-agent'])}`)
  } else {
    access(`${req.method}  ${req.url}  ${new Date().toLocaleString()}  ${req.headers['user-agent']}`)
  }

  res.setHeader('Content-Type', 'application/json; charset=utf-8')

  // 解析req相关
  const url = req.url
  req.path = url.split('?')[0]
  req.query = qs.parse(url.split('?')[1])
  req.cookie = qs.parse(req.headers.cookie, '; ')
  if (req.method === 'POST') req.body = await getPostData(req)

  // 是否需要设置cookie
  let needSetCookie = false
  let userId = req.cookie.userId
  if (!userId) {
    needSetCookie = true
    userId = `${Date.now()}_${parseFloat(Math.random() * 10)}`
    set(userId, {})
  }
  req.sessionId = userId
  const sessionIdData = await get(req.sessionId)
  if (sessionIdData == null) {
    set(req.sessionId, {})
    req.session = {}
  } else {
    req.session = sessionIdData
  }
  
  // 路由处理
  // 博客
  const blogResult = await handleBlogRouter(req, res)
  if (blogResult) {
    if (needSetCookie) {
      res.setHeader('Set-Cookie', `userId=${req.sessionId}; path=/; expires=${getExpires()}; httpOnly`)
    }
    res.end(JSON.stringify(blogResult))
  }

  // 项目
  const itemResult = await handleItemRouter(req, res)
  if (itemResult) {
    if (needSetCookie) {
      res.setHeader('Set-Cookie', `userId=${req.sessionId}; path=/; expires=${getExpires()}; httpOnly`)
    }
    res.end(JSON.stringify(itemResult))
  }

  // user
  const userResult = await handleUserRouter(req, res)
  if (userResult) {
    if (needSetCookie) {
      res.setHeader('Set-Cookie', `userId=${req.sessionId}; path=/; expires=${getExpires()}; httpOnly`)
    }
    res.end(JSON.stringify(userResult))
  }

  // 路由未命中
  const emptyResult = await handleEmptyRouter(req, res)
  res.end(JSON.stringify(emptyResult))
}
